package persistence.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import persistence.db.DataSet;
import persistence.db.DatabaseConnector;
import persistence.model.AbstractModel;
import persistence.model.Groupe;
import persistence.model.Semestre;
import persistence.model.UE;

public class SemestreDAO extends AbstractDAO{
	
	private Semestre semestre;
	
	/**
	 * Constructeur d'un semestreDAO
	 */
	public SemestreDAO(){
		setTableName("SEMESTRE");
	}

	/**
	 * Constructeur d'un semestreDAO
	 * @param sem Semestre corespondant
	 */
	public SemestreDAO(Semestre sem){
		this();
		semestre = sem;
		setId(semestre.getId());
	}
	
	public DataSet all() {
		return new DataSet(this);
	}

	public AbstractModel makeModel(ResultSet rset) {
		try {
			setId(rset.getInt("id_Semestre"));
			
			DataSet ueSet = UE.all().filter("FK_UE_SEMESTRE = " + getId());
			DataSet groupeSet = Groupe.all().filter("FK_GROUPE_SEMESTRE = " + getId());

			String debut = dateToString(rset.getDate("debutSemestre"));
			String fin = dateToString(rset.getDate("finSemestre"));
			
			return new Semestre(getId(),
					rset.getString("nomSemestre"),
					debut,
					fin,
					rset.getInt("nbGpe"),
					rset.getInt("gpePromo"),
					rset.getInt("FK_SEMESTRE_AE"),
					ueSet,
					groupeSet);
		} catch (SQLException e) {
			System.out.println("makeModel error");
			e.printStackTrace();
		}
		return null;
	}

	public void save() {
		String query;
		ResultSet result;
			query = "INSERT INTO " + getTableName() + " VALUES ( S_PK_"+ getTableName() +".nextval, '" +
			semestre.getDebutSemestre() +
			"', '" + semestre.getFinSemestre() +
			"', '" + semestre.getNomSemestre() +
			"', " + semestre.getNbGroupe() +
			", " + semestre.getGroupePromo() +
			", " + semestre.getIdAnneeEtude() + ")";
			/* Execute la requete */
			result = DatabaseConnector.getInstance().execute(query);
			setId(this.getId());
	}

	public void save(int id) {
		String query;
		ResultSet result;
			query = "UPDATE " + getTableName() +
				" SET debutSemestre = '" + semestre.getDebutSemestre() +
					"', finSemestre = '" + semestre.getFinSemestre() +
					"', nomSemestre = '" + semestre.getNomSemestre() +
					
					"', gpePromo = " + semestre.getGroupePromo() +
					", fk_semestre_AE = " + semestre.getIdAnneeEtude() + 
					" WHERE ID_"+ getTableName() + " = " + id;
			/* Execute la requete */
			result = DatabaseConnector.getInstance().execute(query);
	}
}
